//
// Created by mouse on 2019/12/22.
//

#include "Utils.h"

namespace TypeConversionUtils {

    String uint64_to_string(uint64_t number, byte base)
    {
        assert(2 <= base && base <= 36);

        String result = "";

        while (number > 0)
        {
            result = String((uint32_t) (number % base), base) + result;
            number /= base;
        }

        return (result == "" ? "0" : result);
    }

    uint64_t string_to_uint64(const String &string, byte base)
    {
        assert(2 <= base && base <= 36);

        uint64_t result = 0;

        char currentCharacter[1];
        for (uint32_t i = 0; i < string.length(); i++)
        {
            result *= base;
            currentCharacter[0] = string.charAt(i);
            result += strtoul(currentCharacter, NULL, base);
        }

        return result;
    }
}

namespace StringUtils {

    LinkedList<String> split(String s, char seprate)
    {
        LinkedList<String> ret = LinkedList<String>([](String) {});
        uint32_t start = 0;
        uint32_t len = 0;
        for (uint32_t i = 0; i < s.length(); i++)
        {
            if (s[i] == seprate)
            {
                ret.add(s.substring(start, len));
                start = i + 1;
                len = 0;
            } else
            {
                len++;
            }
        }
        if (start < s.length())
            ret.add(s.substring(start, len));
        return ret;
    }

    LinkedList<String> split(String s, String seprate)
    {
        LinkedList<String> ret = LinkedList<String>([](String) {});
        uint32_t seprate_len = seprate.length();
        uint32_t start = 0;
        int index;
        while ((index = s.indexOf(seprate, start)) != -1)
        {
            ret.add(s.substring(start, index - start));
            start = index + seprate_len;
        }
        if (start < s.length())
            ret.add(s.substring(start, s.length() - start));
        return ret;
    }

}